package com.yc.task;

import com.yc.common.utils.HttpsUtils;
import com.yc.mapper.AttendanceRecordsMapper;
import com.yc.mapper.SchoolYearMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import com.yc.common.utils.AllConstans;
import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Stream;

/**
 * @Author dm
 * @Date 2023/8/2 10:19 （可以根据需要修改）
 * @Version 1.0 （版本号）
 */
@Slf4j
@Component
public class SchedTask {

    @Bean
    public TaskScheduler poolScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setThreadNamePrefix("poolScheduler");
        scheduler.setPoolSize(10);
        return scheduler;
    }

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    SchoolYearMapper schoolYearMapper;

    @Autowired
    private AttendanceRecordsMapper attendanceRecordsMapper;


    @Async(value = "asyncPoolTaskExecutor")
    @Scheduled(cron = "0 18 10 L 3,6,8,9,12 ?")
    public void clearRealtimeCacheData() {
        //爬虫
        //获得最新发布的行政日期表
        String test = HttpsUtils.test("https://www.hnit.edu.cn/index/xzrl.htm");
        //获得最新行政日期表中的两学年的第一周开始计算日期
        List<String> strings = HttpsUtils.demo(test);
        assert strings != null;
        for (int i = 0; i < strings.size(); i++) {
            String s = strings.get(i);
            String[] date = s.split(" ");
            //先判断学年是否已经在数据库中存在
            List<String> years = schoolYearMapper.querySchoolYears();
            if (years.contains(date[0])) {
                continue;
            }
            int j = 1;
            //得到接下来20周中相同的周次的时间集合
            List<String> next20WeeksMondays = HttpsUtils.getNext20WeeksMondays(date[1]);
            for (String s1 : next20WeeksMondays) {
                //得到每周天数的集合
                List<String> otherDatesInSameWeek = HttpsUtils.getOtherDatesInSameWeek(s1);
                //批量添加
                schoolYearMapper.insertTimeData(otherDatesInSameWeek, j++, date[0]);
            }
        }
    }

    /**
     *  计算学生个人得分
     * @param stuid 学生id
     * @return 该状态的次数
     */
    public int finalscore(String stuid) {
        int latecount = attendanceRecordsMapper.StatusCount(stuid, 3);// 查询迟到的次数
        int Earlycount = attendanceRecordsMapper.StatusCount(stuid,4);// 查询早退的次数
        int truancycount = attendanceRecordsMapper.StatusCount(stuid,5);// 查询旷课的次数
        int subtractscore = 0;// 要减去的分数（初始为0
        int finalscore = 50;// 最终分数（默认50分满分
        // 计算要扣除的分数
        subtractscore = (latecount+Earlycount)/3 + truancycount;//迟到和早退满三次扣一分 旷课直接扣一分
        finalscore = finalscore - subtractscore;
        return finalscore;// 返回最终分数
    }

    /**
     * 定时（每年每月每日凌晨2.）计算学生的个人评分
     *
     */
    @Async(value = "asyncPoolTaskExecutor")
    @Scheduled(cron = "0 0 2 * * *")
    public void clearRealtimeCacheData2() {
        log.warn(" start clearRealtimeCacheData2 ");
        List<String> allclass = attendanceRecordsMapper.selectallclass();
        Map<String,Object> stuidinclass = new HashMap<>();
        for (String cid : allclass) {
            List<Map<String,Object>> stuid = attendanceRecordsMapper.selectstuidbycid(cid);
            List<Map<String,Object>> restuid = new ArrayList<>();
            for (Map<String, Object> idmap : stuid) {
                String sid = (String) idmap.get("stuid");
                int finalscore = finalscore(sid);
                Map<String,Object> idandscore = new HashMap<>();
                idandscore.put("stuid",sid);
                idandscore.put("finalscore",finalscore);
                restuid.add(idandscore);
            }
            stuidinclass.put(cid,restuid);
        }
        redisTemplate.opsForValue().set("AllStuScoreData",stuidinclass);// 存入redis
    }

    /**
     * 删除当天的二维码文件夹 定于每日凌晨1点
     */
    @Async(value = "asyncPoolTaskExecutor")
    @Scheduled(cron = "0 0 1 * * *")
    public void removeQRCode(){
        String path = AllConstans.STU_UPLOAD_PATH + "/qrcode";
        Path filePath = Paths.get(path);

        try (Stream<Path> walk = Files.walk(filePath)){
            walk.sorted(Comparator.reverseOrder()).forEach((file)->{
                deleteDirectoryStream(file);
            });
        }catch (IOException e){
            e.printStackTrace();
        }
    }


    // 删除文件
    private static void deleteDirectoryStream(Path path) {
        try {
            Files.delete(path);
            System.out.printf("删除文件成功：%s%n",path.toString());
        } catch (IOException e) {
            System.err.printf("无法删除的路径 %s%n%s", path, e);
        }
    }
}

